"use client";
import { useState, useEffect, useCallback, useMemo } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { Form, Input, Button, Select, Switch, Card, Space, Breadcrumb, Typography, Upload, Skeleton, Modal, Divider, Image } from "antd";
import { useMessage } from '@/hooks/useMessage';
import type { UploadProps } from "antd";
import { PlusOutlined, SaveOutlined, ArrowLeftOutlined, LoadingOutlined, EyeOutlined } from "@ant-design/icons";
import type { RcFile } from "antd/es/upload/interface";
import { adminAPI, ossAPI } from "@/lib/api";
import type { ProductCategory } from "@/lib/api";
import AdminLayout from "@/components/AdminLayout";
import dynamic from "next/dynamic";
import { debounce } from "lodash";

// 动态导入ArticleEditor，避免服务端渲染问题
const ArticleEditor = dynamic(() => import("@/components/ArticleEditor"), {
  ssr: false,
  loading: () => <Skeleton active paragraph={{ rows: 8 }} />,
});

const { TextArea } = Input;
const { Option } = Select;
const { Title } = Typography;

function ProductEditForm() {
  const message = useMessage();
  const router = useRouter();
  const searchParams = useSearchParams();
  const productId = searchParams.get("id");
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [html, setHtml] = useState("");
  const [categories, setCategories] = useState<ProductCategory[]>([]);
  const [coverImageUrl, setCoverImageUrl] = useState<string>();
  const [screenshots, setScreenshots] = useState<string[]>([]);
  const [uploadingScreenshots, setUploadingScreenshots] = useState(false);
  const [uploadingAvatar, setUploadingAvatar] = useState(false);
  const [developerAvatarUrl, setDeveloperAvatarUrl] = useState<string>();
  const [isCategoryModalVisible, setIsCategoryModalVisible] = useState(false);
  const [newCategoryName, setNewCategoryName] = useState("");

  const isEdit = !!productId;

  // 获取分类列表
  const loadCategories = useCallback(async () => {
    try {
      const response = await adminAPI.getProductCategories();
      if (response.success) {
        setCategories(response.data);
      }
    } catch (error) {
      console.error("获取产品分类失败:", error);
      message.error("获取产品分类失败");
    }
  }, [message]);

  // 添加新分类
  const handleAddCategory = useCallback(async () => {
    if (!newCategoryName.trim()) {
      message.error("分类名称不能为空");
      return;
    }
    try {
      const res = await adminAPI.createProductCategory({ name: newCategoryName });
      if (res.success) {
        message.success("分类添加成功");
        setIsCategoryModalVisible(false);
        setNewCategoryName("");
        loadCategories();
      } else {
        message.error(res.error || "添加失败");
      }
    } catch (error) {
      console.error("添加产品分类失败:", error);
      message.error("添加产品分类失败");
    }
  }, [newCategoryName, message, loadCategories]);

  // 获取产品数据
  const loadProductData = useCallback(async (id: string) => {
    setLoading(true);
    try {
      const productIdNum = parseInt(id);
      if (isNaN(productIdNum)) {
        message.error("无效的产品ID");
        return;
      }
      const response = await adminAPI.getProductById(productIdNum);
      if (response.success) {
        const productData = response.data;
        setHtml(productData.content);
        if (productData.coverImage) {
          setCoverImageUrl(productData.coverImage);
        }
        if (productData.screenshots) {
          setScreenshots(productData.screenshots);
        }
        form.setFieldsValue({
          title: productData.title,
          summary: productData.summary,
          categoryId: productData.categoryId,
          status: productData.status,
          isTop: productData.isTop,
          isRecommend: productData.isRecommend,
          author: productData.author,
          websiteUrl: productData.websiteUrl,
          developerAvatar: productData.developerAvatar,
          developerNickname: productData.developerNickname,
          developerBio: productData.developerBio,
        });
        setDeveloperAvatarUrl(productData.developerAvatar);
      }
    } catch (error) {
      console.error("获取产品数据失败:", error);
      message.error("获取产品数据失败");
    } finally {
      setLoading(false);
    }
  }, [form, message]);

  // 保存产品的核心逻辑
  const handleSaveCore = useCallback(async (shouldReturn = false) => {
    try {
      const values = await form.validateFields();
      setLoading(true);

      const productData = {
        ...values,
        content: html,
        coverImage: coverImageUrl,
        screenshots: screenshots,
        author: values.author || "管理员",
        developerAvatar: developerAvatarUrl,
        developerNickname: values.developerNickname,
        developerBio: values.developerBio,
      };

      if (productId) {
        // 更新产品
        const productIdNum = parseInt(productId);
        if (isNaN(productIdNum)) {
          message.error("无效的产品ID");
          return;
        }
        const response = await adminAPI.updateProduct(productIdNum, productData);
        if (response.success) {
          message.success("产品更新成功");
          if (shouldReturn) {
            router.push("/admin/products");
          }
        } else {
          message.error(response.error || "更新失败");
        }
      } else {
        // 创建产品
        const response = await adminAPI.createProduct(productData);
        if (response.success) {
          message.success("产品创建成功");
          if (shouldReturn) {
            router.push("/admin/products");
          }
        } else {
          message.error(response.error || "创建失败");
        }
      }
    } catch (error) {
      console.error("保存产品失败:", error);
      message.error("保存失败");
    } finally {
      setLoading(false);
    }
  }, [form, html, coverImageUrl, screenshots, developerAvatarUrl, productId, message, router]);

  // 使用防抖处理的保存函数
  const handleSave = useMemo(
    () => debounce(handleSaveCore, 1000, { leading: true, trailing: false }),
    [handleSaveCore]
  );

  // 处理图片上传
  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    if (!isJpgOrPng) {
      message.error("你只能上传 JPG/PNG 格式的图片!");
    }
    const isLt2M = file.size / 1024 / 1024 < 10;
    if (!isLt2M) {
      message.error("图片大小必须小于 10MB!");
    }
    return isJpgOrPng && isLt2M;
  };

  // 处理截图上传
  const beforeScreenshotUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    if (!isJpgOrPng) {
      message.error("你只能上传 JPG/PNG 格式的图片!");
      return false;
    }
    const isLt2M = file.size / 1024 / 1024 < 10;
    if (!isLt2M) {
      message.error("图片大小必须小于 10MB!");
      return false;
    }
    if (screenshots.length >= 10) {
      message.error("最多只能上传10张截图!");
      return false;
    }
    return isJpgOrPng && isLt2M;
  };

  // 自定义上传处理
  type CustomRequestOptions = Parameters<Required<UploadProps>["customRequest"]>[0];

  const handleCustomRequest = async (options: CustomRequestOptions) => {
    const { file, onSuccess, onError } = options;
    setUploadingScreenshots(true);
    try {
      const res = await ossAPI.getSign();
      if (!res.success) {
        const error = new Error("获取上传签名失败");
        message.error("获取上传签名失败");
        if (onError) onError(error);
        return;
      }

      const { accessKeyId, policy, signature, dir, host } = res.data;
      const key = `${dir}${Date.now()}-${(file as RcFile).name}`;

      const formData = new FormData();
      formData.append("key", key);
      formData.append("policy", policy);
      formData.append("OSSAccessKeyId", accessKeyId);
      formData.append("success_action_status", "200");
      formData.append("signature", signature);
      formData.append("file", file);

      const uploadRes = await fetch(host, {
        method: "POST",
        body: formData,
      });

      if (uploadRes.ok) {
        const imageUrl = `${host}/${key}`;
        setCoverImageUrl(imageUrl);
        message.success("封面上传成功");
        if (onSuccess) {
          onSuccess({ url: imageUrl });
        }
      } else {
        throw new Error("上传失败");
      }
    } catch (err) {
      const error = err as Error;
      console.error("上传图片失败:", error);
      message.error("上传图片失败");
      if (onError) onError(error);
    } finally {
      setUploadingScreenshots(false);
    }
  };

  // 处理截图上传
  const handleScreenshotUpload = async (options: CustomRequestOptions) => {
    const { file, onSuccess, onError } = options;
    setUploadingScreenshots(true);
    try {
      const res = await ossAPI.getSign();
      if (!res.success) {
        const error = new Error("获取上传签名失败");
        message.error("获取上传签名失败");
        if (onError) onError(error);
        return;
      }

      const { accessKeyId, policy, signature, dir, host } = res.data;
      const key = `${dir}screenshots/${Date.now()}-${(file as RcFile).name}`;

      const formData = new FormData();
      formData.append("key", key);
      formData.append("policy", policy);
      formData.append("OSSAccessKeyId", accessKeyId);
      formData.append("success_action_status", "200");
      formData.append("signature", signature);
      formData.append("file", file);

      const uploadRes = await fetch(host, {
        method: "POST",
        body: formData,
      });

      if (uploadRes.ok) {
        const imageUrl = `${host}/${key}`;
        setScreenshots(prev => [...prev, imageUrl]);
        message.success("截图上传成功");
        if (onSuccess) {
          onSuccess({ url: imageUrl });
        }
      } else {
        throw new Error("上传失败");
      }
    } catch (err) {
      const error = err as Error;
      console.error("上传截图失败:", error);
      message.error("上传截图失败");
      if (onError) onError(error);
    } finally {
      setUploadingScreenshots(false);
    }
  };

  // 处理开发者头像上传
  const handleDeveloperAvatarUpload = async (options: CustomRequestOptions) => {
    const { file, onSuccess, onError } = options;
    setUploadingAvatar(true);
    try {
      const res = await ossAPI.getSign();
      if (!res.success) {
        const error = new Error("获取上传签名失败");
        message.error("获取上传签名失败");
        if (onError) onError(error);
        return;
      }

      const { accessKeyId, policy, signature, dir, host } = res.data;
      const key = `${dir}avatars/${Date.now()}-${(file as RcFile).name}`;

      const formData = new FormData();
      formData.append("key", key);
      formData.append("policy", policy);
      formData.append("OSSAccessKeyId", accessKeyId);
      formData.append("success_action_status", "200");
      formData.append("signature", signature);
      formData.append("file", file);

      const uploadRes = await fetch(host, {
        method: "POST",
        body: formData,
      });

      if (uploadRes.ok) {
        const imageUrl = `${host}/${key}`;
        setDeveloperAvatarUrl(imageUrl);
        form.setFieldsValue({ developerAvatar: imageUrl });
        message.success("开发者头像上传成功");
        if (onSuccess) {
          onSuccess({ url: imageUrl });
        }
      } else {
        throw new Error("上传失败");
      }
    } catch (err) {
      const error = err as Error;
      console.error("上传开发者头像失败:", error);
      message.error("上传开发者头像失败");
      if (onError) onError(error);
    } finally {
      setUploadingAvatar(false);
    }
  };

  // 初始化
  useEffect(() => {
    loadCategories();
    if (isEdit && productId) {
      loadProductData(productId);
    }
  }, [isEdit, productId, loadCategories, loadProductData]);

  return (
    <AdminLayout>
      <Card>
        <div style={{ marginBottom: 24 }}>
          <Breadcrumb items={[{ title: "产品管理", href: "/admin/products" }, { title: isEdit ? "编辑产品" : "新建产品" }]} />
        </div>

        <div style={{ marginBottom: 16, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <Title level={3} style={{ margin: 0 }}>
            {isEdit ? "编辑产品" : "新建产品"}
          </Title>
          <Space>
            <Button icon={<ArrowLeftOutlined />} onClick={() => router.push("/admin/products")}>
              返回列表
            </Button>
            <Button icon={<SaveOutlined />} onClick={() => handleSave(false)} loading={loading}>
              {isEdit ? "更新" : "保存"}
            </Button>
            <Button type='primary' icon={<SaveOutlined />} onClick={() => handleSave(true)} loading={loading}>
              {isEdit ? "更新并返回" : "保存并返回"}
            </Button>
          </Space>
        </div>

        <Form form={form} layout='vertical' initialValues={{ status: true, isTop: false, isRecommend: false, author: "管理员" }} className='space-y-8'>
          <div className='grid grid-cols-1 xl:grid-cols-3 gap-8'>
            {/* 主内容区（左2/3） */}
            <div className='xl:col-span-2 space-y-8'>
              {/* 基础信息卡片 */}
              <div className='bg-white rounded-xl shadow-sm border border-slate-200 p-8'>
                <h3 className='text-xl font-semibold text-slate-800 mb-6 pb-3 border-b border-slate-100'>基础信息</h3>
                <Form.Item name='title' label={<span className='text-slate-700 font-medium'>产品名称</span>} rules={[{ required: true, message: "请输入产品名称" }]} className='mb-6'>
                  <Input placeholder='请输入产品名称' size='large' className='rounded-lg border-slate-300 focus:border-blue-500 focus:ring-blue-500 h-12 text-lg' />
                </Form.Item>
                <Form.Item name='summary' label={<span className='text-slate-700 font-medium'>一句话简介</span>} className='mb-6'>
                  <TextArea rows={2} placeholder='简要描述产品亮点（可选）' maxLength={1000} showCount className='rounded-lg border-slate-300 focus:border-blue-500 focus:ring-blue-500' />
                </Form.Item>
                <div className='grid grid-cols-1 md:grid-cols-2 gap-6 mb-6'>
                  <Form.Item name='categoryId' label={<span className='text-slate-700 font-medium'>分类</span>} rules={[{ required: true, message: "请选择分类" }]}>
                    <Select
                      placeholder='请选择分类'
                      className='rounded-lg'
                      popupRender={menu => (
                        <>
                          {menu}
                          <Divider style={{ margin: "8px 0" }} />
                          <Button type='text' icon={<PlusOutlined />} onClick={() => setIsCategoryModalVisible(true)}>
                            添加分类
                          </Button>
                        </>
                      )}
                    >
                      {categories.map(category => (
                        <Option key={category.id} value={category.id}>
                          {category.name}
                        </Option>
                      ))}
                    </Select>
                  </Form.Item>
                  <Form.Item name='author' label={<span className='text-slate-700 font-medium'>作者</span>} rules={[{ required: true, message: "请输入作者" }]}>
                    <Input placeholder='请输入作者' className='rounded-lg border-slate-300 focus:border-blue-500 focus:ring-blue-500' />
                  </Form.Item>
                </div>
                <Form.Item name='websiteUrl' label={<span className='text-slate-700 font-medium'>官网链接</span>} className='mb-6'>
                  <Input placeholder='请输入官网链接' className='rounded-lg border-slate-300 focus:border-blue-500 focus:ring-blue-500' />
                </Form.Item>
                <div className='flex flex-col md:flex-row gap-8 items-start'>
                  <Form.Item label={<span className='text-slate-700 font-medium'>产品Logo</span>} className='flex-1'>
                    <Upload name='cover' listType='picture-card' showUploadList={false} customRequest={handleCustomRequest} beforeUpload={beforeUpload} className='rounded-lg overflow-hidden'>
                      {coverImageUrl ? (
                        <img src={coverImageUrl} alt='产品Logo' style={{ width: "100%", height: "100%", objectFit: "cover" }} />
                      ) : (
                        <div className='flex flex-col items-center justify-center h-full'>
                          <PlusOutlined className='text-2xl text-slate-400 mb-2' />
                          <span className='text-sm text-slate-500'>上传Logo</span>
                        </div>
                      )}
                    </Upload>
                  </Form.Item>
                  <div className='flex-1 flex flex-col gap-4'>
                    <Form.Item name='status' label={<span className='text-slate-700 font-medium'>状态</span>} valuePropName='checked'>
                      <Switch checkedChildren='已发布' unCheckedChildren='草稿' className='bg-slate-300' />
                    </Form.Item>
                    <Form.Item name='isTop' label={<span className='text-slate-700 font-medium'>置顶</span>} valuePropName='checked'>
                      <Switch checkedChildren='置顶' unCheckedChildren='普通' className='bg-slate-300' />
                    </Form.Item>
                    <Form.Item name='isRecommend' label={<span className='text-slate-700 font-medium'>推荐</span>} valuePropName='checked'>
                      <Switch checkedChildren='推荐' unCheckedChildren='普通' className='bg-slate-300' />
                    </Form.Item>
                  </div>
                </div>
              </div>

              {/* 产品详情卡片 */}
              <div className='bg-white rounded-xl shadow-sm border border-slate-200 p-8'>
                <h3 className='text-xl font-semibold text-slate-800 mb-6 pb-3 border-b border-slate-100'>产品详情</h3>
                <Form.Item label={<span className='text-slate-700 font-medium'>产品详情</span>} required>
                  <ArticleEditor key={productId || "create"} value={html} onChange={setHtml} />
                </Form.Item>
              </div>

              {/* 产品截图卡片 */}
              <div className='bg-white rounded-xl shadow-sm border border-slate-200 p-8'>
                <h3 className='text-xl font-semibold text-slate-800 mb-6 pb-3 border-b border-slate-100'>产品截图</h3>
                <div className='text-sm text-slate-600 mb-4'>最多上传10张截图，支持JPG/PNG格式，单张不超过10MB</div>
                <div className='space-y-4'>
                  {screenshots.length > 0 && (
                    <div className='grid grid-cols-2 md:grid-cols-4 lg:grid-cols-5 gap-4'>
                      {screenshots.map((url, index) => (
                        <div
                          key={index}
                          className='relative group cursor-move'
                          draggable
                          onDragStart={e => {
                            e.dataTransfer.setData("text/plain", index.toString());
                          }}
                          onDragOver={e => {
                            e.preventDefault();
                          }}
                          onDrop={e => {
                            e.preventDefault();
                            const fromIndex = parseInt(e.dataTransfer.getData("text/plain"));
                            const toIndex = index;
                            if (fromIndex !== toIndex) {
                              const newScreenshots = [...screenshots];
                              const [movedItem] = newScreenshots.splice(fromIndex, 1);
                              newScreenshots.splice(toIndex, 0, movedItem);
                              setScreenshots(newScreenshots);
                              message.success("截图顺序已更新");
                            }
                          }}
                          style={{ userSelect: "none" }}
                        >
                          <div className='relative w-full h-32 cursor-pointer overflow-hidden rounded-lg border border-slate-200 hover:border-blue-300 transition-colors shadow-sm' style={{ userSelect: "none" }}>
                            <Image
                              src={url}
                              alt={`截图 ${index + 1}`}
                              className='w-full h-full object-cover transition-transform duration-200 group-hover:scale-105'
                              style={{
                                pointerEvents: "none",
                                userSelect: "none",
                                WebkitUserSelect: "none",
                                MozUserSelect: "none",
                                msUserSelect: "none",
                              }}
                              preview={{
                                mask: null,
                                maskClassName: "hidden",
                              }}
                            />
                            <div className='absolute top-2 right-2 flex space-x-1 z-10'>
                              <button
                                type='button'
                                onClick={e => {
                                  e.stopPropagation();
                                  // 直接点击Image组件来触发预览
                                  const imageElement = e.currentTarget.parentElement?.parentElement?.querySelector("img");
                                  if (imageElement) {
                                    imageElement.click();
                                  }
                                }}
                                className='w-6 h-6 bg-slate-400 hover:bg-slate-500 text-white rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity shadow-sm'
                                title='预览'
                              >
                                <EyeOutlined />
                              </button>
                              <button
                                type='button'
                                onClick={e => {
                                  e.stopPropagation();
                                  const newUrls = screenshots.filter((_, i) => i !== index);
                                  setScreenshots(newUrls);
                                  message.success("截图删除成功");
                                }}
                                className='w-6 h-6 bg-slate-400 hover:bg-slate-500 text-white rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity shadow-sm'
                                title='删除'
                              >
                                ×
                              </button>
                            </div>
                            <div className='absolute bottom-2 left-2 bg-black bg-opacity-50 text-white text-xs px-2 py-1 rounded-full z-10'>{index + 1}</div>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                  {screenshots.length < 10 && (
                    <Upload name='screenshots' listType='picture-card' customRequest={handleScreenshotUpload} beforeUpload={beforeScreenshotUpload} accept='image/jpeg,image/png' multiple={true} showUploadList={false} className='rounded-lg overflow-hidden'>
                      <div className='flex flex-col items-center justify-center h-full'>
                        {uploadingScreenshots ? <LoadingOutlined className='text-2xl text-slate-400 mb-2' /> : <PlusOutlined className='text-2xl text-slate-400 mb-2' />}
                        <div className='text-sm text-slate-500'>上传截图</div>
                      </div>
                    </Upload>
                  )}
                </div>
                {screenshots.length > 0 && <div className='text-sm text-slate-500 mt-4 p-3 bg-slate-50 rounded-lg'>已上传 {screenshots.length}/10 张截图，拖拽图片可调整顺序，点击图片可预览</div>}
              </div>
            </div>

            {/* 右侧辅助栏 */}
            <div className='space-y-8'>
              {/* 开发者信息卡片 */}
              <div className='bg-white rounded-xl shadow-sm border border-slate-200 p-8'>
                <h3 className='text-xl font-semibold text-slate-800 mb-6 pb-3 border-b border-slate-100'>开发者信息</h3>
                <Form.Item label={<span className='text-slate-700 font-medium'>开发者昵称</span>} name='developerNickname' rules={[{ required: false, message: "请输入开发者昵称" }]} className='mb-6'>
                  <Input placeholder='请输入开发者昵称' className='rounded-lg border-slate-300 focus:border-blue-500 focus:ring-blue-500' />
                </Form.Item>
                <Form.Item label={<span className='text-slate-700 font-medium'>开发者头像</span>} name='developerAvatar' rules={[{ required: false, message: "请输入开发者头像URL" }]} className='mb-6'>
                  <Upload name='developerAvatar' listType='picture-circle' showUploadList={false} customRequest={handleDeveloperAvatarUpload} beforeUpload={beforeUpload} className='rounded-full overflow-hidden'>
                    {developerAvatarUrl ? (
                      <img src={developerAvatarUrl} alt='开发者头像' style={{ width: "100%", height: "100%", objectFit: "cover", borderRadius: "50%" }} />
                    ) : (
                      <div className='flex flex-col items-center justify-center h-full'>
                        {uploadingAvatar ? <LoadingOutlined className='text-xl text-slate-400 mb-1' /> : <PlusOutlined className='text-xl text-slate-400 mb-1' />}
                        <span className='text-xs text-slate-500'>{uploadingAvatar ? '上传中...' : '上传头像'}</span>
                      </div>
                    )}
                  </Upload>
                </Form.Item>
                <Form.Item label={<span className='text-slate-700 font-medium'>开发者介绍</span>} name='developerBio' rules={[{ required: false, message: "请输入开发者介绍" }]}>
                  <TextArea rows={4} placeholder='请输入开发者介绍，描述开发者的背景、专长等' maxLength={500} showCount className='rounded-lg border-slate-300 focus:border-blue-500 focus:ring-blue-500' />
                </Form.Item>
              </div>
            </div>
          </div>
        </Form>
      </Card>

      <Modal title='添加新分类' open={isCategoryModalVisible} onOk={handleAddCategory} onCancel={() => setIsCategoryModalVisible(false)}>
        <Input value={newCategoryName} onChange={e => setNewCategoryName(e.target.value)} placeholder='请输入新的分类名称' />
      </Modal>
    </AdminLayout>
  );
}

export default function ProductEditPage() {
  return (
    <Skeleton active loading={false}>
      <ProductEditForm />
    </Skeleton>
  );
}
